package cn.ynrcb.personnelfile.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.io.resource.Resource;
import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpUtil;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileUtils {

    public static final int fileSize = 10 * 1024;

    public static void download(String filename, HttpServletResponse res) throws IOException {
        String templateFilePath = "/template/" + filename;
        Resource resource = new ClassPathResource(templateFilePath);
        // 发送给客户端的数据
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取filename
//        bis = new BufferedInputStream(new FileInputStream(new File(filename)));
        bis = new BufferedInputStream(resource.getStream());    // 将模板文件转换为文件流
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }

        bis.close();
        outputStream.close();
    }

    /**
     * 获取当前系统根目录
     *
     * @return
     * @author swb
     * @version created at 2020年8月25日 下午2:36:24
     */
    public static String getUploadPath() {
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (!path.exists()) path = new File("");
        File upload = new File(path.getAbsolutePath(), "static/upload/");
        if (!upload.exists()) upload.mkdirs();
        return upload.getAbsolutePath();
    }

    /**
     * 检查文件目录是否存在
     *
     * @param file
     * @author swb
     * @version created at 2020年4月14日 上午10:33:22
     */
    public static void checkExist(File file) {
        if (file.getParentFile().exists()) {
            file.mkdir();
        } else {
            checkExist(file.getParentFile());
            file.mkdir();
        }
    }

    public static void remoteDownloadFile(String url, String path) {
        checkExist(new File(path));
        long size = HttpUtil.downloadFile(url, FileUtil.file(path));
        Console.log("下载文件大小：" + size);
    }

    public static void downloadFile(String remoteFilePath, String localFilePath) {
        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try {
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @Author swb
     * @Description //TODO 本地文件下载
     * @Date 14:25 14:25
     * @Param [filePath, fileName, response]
     * @return boolean
     **/
    public static boolean downloadLocalFile(String filePath, String fileName, HttpServletResponse response) {
        File file = new File(filePath + fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            byte[] buffer = new byte[fileSize];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }

    /**
     * 删除单个文件
     *
     * @param fileName
     *            要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
//		remoteDownloadFile("http://116.53.196.230:8002/WebPortal/Api/WebDownLoad/GetFileFromWebApi?FuJianID=1a7fa70a-bf0f-4ed2-92a2-707447f2202a", "G:/uploadfile/maibox/download/");
//		downloadFile("http://116.53.196.230:8002/WebPortal/Api/WebDownLoad/GetFileFromWebApi?FuJianID=1a7fa70a-bf0f-4ed2-92a2-707447f2202a", "G:/uploadfile/maibox/download/图片资");
    }

}
